<?php
namespace cms\modules\v1\models\gift;

use common\models\CacheKeys;
use common\models\Functions;
use common\models\Status;
use yii\base\Exception;
use Yii;
use yii\helpers\StringHelper;

class GiftCategory extends \common\models\gift\GiftCategory
{

    public function rules()
    {
        return [
            #添加
            [['name'],  'required', 'message' => '{attribute}不能空', 'on' => 'addEdit'],
            [['name',],'filter','filter' => 'trim', 'on' => ['addEdit']],
            ['name', 'string','min' => 0,'max' => 20,"tooLong"=>"限制20字", "tooShort"=>"不能为空",'on' => 'addEdit'],

        ];
    }

    public function scenarios()
    {
        $newScenarios =  [
            'addEdit' => [
                'name',
            ],
        ];
        return array_merge(parent::scenarios(), $newScenarios);
    }

    /**
     * 起别名
     */
    public function attributeLabels()
    {
        return [
            'name' => '名称',
        ];
    }


    /**
     * 返回列表数据
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getListData($page = 1, $size = 20) {
        try {
            //搜索条件
            $searchWhere  = $this->getSearch();//自定义搜索条件
            //得到文章的总数
            $count = static::getObjectCountByAndWhere($searchWhere['where'], $searchWhere['andWhere'])->count();
            $data = static::setPageinationAPI($page, $size, $count);
            //设置分页
            $offset = ($page - 1) * $size;

            //排序 order
            $orderSql = 'id ASC';

            $query = static::getObjectByAndWhere($searchWhere['where'],$searchWhere['andWhere'], '*', $orderSql, $offset, $size);
            $data['data'] = $this->handelList($query);

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 自定义参数的搜索  搜索,搜索也分每一列
     * 这里要根据业务逻辑进行修改
     */
    public function getSearch () {
        $where = [];
        $andWhere = [];
//        $where['is_delete'] = Status::COMMON_IS_NOT_DELETE;

        $startTime = Yii::$app->request->get('start','');
        $endTime = Yii::$app->request->get('end','');
        $status = Yii::$app->request->get('status','');

        if ($status) {
            $where['status'] = (int) $status;
        }

        if(!empty($startTime) && empty($endTime)) {
            $andWhere = ['>','create_time',$startTime];
        } elseif(empty($startTime) && !empty($endTime)) {
            $andWhere = ['<','create_time',$endTime];
        } elseif (!empty($startTime) && !empty($endTime)) {
            $andWhere = ['between','create_time',$startTime, $endTime];
        }

        return [
            'where' => $where,
            'andWhere' => $andWhere,
        ];
    }

    /**
     * 处理初始化数据
     * @param $query
     * @return mixed
     */
    public function handelList($query = null) {
        if (empty($query)) {
            return null;
        }
        $list = $query->with()->asArray()->all();

        foreach ($list as &$v) {
            $v['time'] = $v['update_time'] ?: $v['create_time'];
        }
        return $list;
    }

    /**
     * 添加修改
     * @return array
     */
    public function addEdit() {
        $trans = Yii::$app->db->beginTransaction();
        try {
            if (!$this->validate()) {
                throw new Exception($this->getErrorSummary(true)[0]);
            }

            $id = Yii::$app->request->post('id',0);
            $post = Yii::$app->request->post();
            $data = [];
            $data = array_merge($data, $this->getSaveData($this->scenario, $post));

            if (!empty($id)) {
                //更新操作

                $data['update_time'] = date('Y-m-d H:i:s');

                $res = static::updateDataWithLog($data, ['id' => $id]);
                if ($res === false) {
                    throw new Exception('更新失败');
                }
            } else {
                //添加操作
                $data['update_time'] = $data['create_time'] = date('Y-m-d H:i:s');

                $res = static::insertDataWithLog($data);
                if ($res === false) {
                    throw new Exception('添加失败');
                }
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 获取信息
     * @param int $id
     *
     * @return array
     */
    public function getInfo($id = 0) {
        try {
            $id = (int) $id;
            if (empty($id)) {
                throw new Exception('信息不存在');
            }

            $info = static::getOneInfoById($id);
            if (empty($info)) {
                throw new Exception('信息不存在');
            }

            $data['name'] = $info['name'];

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 启用禁用 等切换装填
     * @return array
     */
    public function setField()
    {
        try {
            $isDelete = Yii::$app->request->post('is_delete','');
            $status = Yii::$app->request->post('status','');
            $listOrder = Yii::$app->request->post('list_order','');
            $id = Yii::$app->request->post('id',0);
            if (empty($id)) {
                throw new Exception('未知信息');
            }

            if ($status) {
                $data['status'] = (int) $status;
            }

            if ($isDelete) {
                $data['is_delete'] = (int) $isDelete;
            }

            if ($listOrder) {
                $data['list_order'] = (int) $listOrder;
            }

            $data['update_time'] = date("Y-m-d H:i:s");
            $res = static::updateData($data, ['id' => $id]);
            if ($res === false) {
                throw new Exception('操作失败');
            }
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }
}
